"use strict";

module.exports = core;
// require支持.js/.json/.node三种文件格式
//其它文件用require引入也会当.js文件处理
const fs = require("fs");
const path = require("path");
const pkg = require("../package.json");
const log = require("@yk-cli-dev/log");
const constant = require("./constant");
const semver = require("semver");
const os = require("os");
const userHome = require("user-home");
// const pathExists=require('path-exists').sync
const colors = require("colors/safe");
const commander = require("commander");
const init = require("@yk-cli-dev/init");
const exec = require("@yk-cli-dev/exec");
let args, config;
const program = new commander.Command();
async function core() {
  try {
    await prepare();
    registerCommand();
  } catch (error) {
    console.log(error.message);
    console.log(error);
  }
}
async function prepare() {
  checkPkgVersion();
  // checkNodeVersion();
  checkRoot;
  checkUserHome();
  // checkInputArgs();
  checkEnv();
  checkGlobalUpdate();
}
//检查package版本
function checkPkgVersion() {
  console.log(pkg.version);
}
//检查node版本
function checkNodeVersion() {
  const currentVersion = process.version;
  const lowestVersion = constant.LOWEST_NODE_VERSION;
  if (!semver.gte(currentVersion, lowestVersion)) {
    // throw new Error(colors.red(`yk-cli-dev 需要安装 v${lowestVersion} 以上版本的 node`))
    throw new Error(
      log.error(`yk-cli-dev 需要安装 v${lowestVersion} 以上版本的 node`)
    );
  }
}
//检查root版本
function checkRoot() {
  if (process.geteuid) {
    const rootCheck = require("root-check");
    rootCheck();
  } else {
    console.log(os.userInfo().username);
  }
}

function checkUserHome() {
  // console.log(userHome);
  if (!userHome) {
    throw new Error(colors.red("当前登录用户主目录不存在"));
  }
}
//检查入参
function checkInputArgs() {
  const minimist = require("minimist");
  args = minimist(process.argv.slice(2));
  checkArgs();
}

function checkArgs() {
  if (args.debug) {
    process.env.LOG_LEVEL = "verbose";
  } else {
    process.env.LOG_LEVEL = "info";
  }
  log.level = process.env.LOG_LEVEL;
}
//检查环境变量
function checkEnv() {
  const dotenv = require("dotenv");
  dotenv.config({
    path: path.resolve(__dirname, "../../../.env"),
  });
  log.verbose("config==环境变量", config, process.env.CLI_HOME);
  createDefaultConfig();
}
//创建环境变量
function createDefaultConfig() {
  const cliConfig = {
    home: userHome,
  };
  if (!process.env.CLI_HOME) {
    // cliConfig.cliHome = path.join(userHome, process.env.CLI_HOME)
    // BASE_URL="http://localhost/:7002"
    const envFilePath = path.join(__dirname, "../../../.env");
    fs.writeFileSync(envFilePath, `CLI_HOME="${constant.DEFAULT_CLI_HOME}"\nBASE_URL="${constant.BASE_URL}"`);
    // fs.writeFileSync(envFilePath, `BASE_URL="${constant.BASE_URL}"`);
  }
  cliConfig.cliHome = path.join(__dirname, "../../../.env");
  process.env.CLI_HOME_PATH = path.join(__dirname, "../../../");
}
async function checkGlobalUpdate() {
  //1. 获取当前版本号和模块名
  const currentVersion = pkg.version;
  const npmName = pkg.name;
  //2. 调用npm API 获取所有版本号
  const { getNpmInfo, getNpmVersion, getNpmLastestVersion } = await import(
    "@yk-cli-dev/get-npm"
  );

  const resulte = await getNpmInfo(npmName);
  //3. 提取所有版本号，对比哪些版本号是大于当前版本号
  const data = await getNpmVersion(npmName);
  const newVersions = await getNpmLastestVersion(currentVersion, npmName);
  // console.log(resulte,'??-',data);
  //4.获取最新版本号，提示该用户跟新到该版本
  if (newVersions && semver.gt(newVersions, currentVersion)) {
    log.warn(
      `请手动更新${npmName},当前版本：${currentVersion},最新版本:${newVersions},更新命令：npm install -g ${npmName}`
    );
  }
}
//参数解析
function registerCommand() {
  program
    .storeOptionsAsProperties()
    .version(pkg.version)
    .name(Object.keys(pkg.bin)[0])
    .usage("<command> [options]")
    .option("-d, --debug", "是否开启调试模式", false)
    .option("-tp, --targetPath <targetPath>", "是否指定本地调试文件路径", "");
  program
    .command("init [projectName]")
    .option("-f, --force", "是否强制初始化项目", false)
    .action(exec);
  program.on("option:debug", (s) => {
    console.log();
    if (!program.debug) return (process.env.LOG_LEVEL = "info");
    process.env.LOG_LEVEL = "verbose";
    log.level = process.env.LOG_LEVEL;
  });
  //指定targetPath
  program.on("option:targetPath", (targetPath) => {
    console.log(targetPath, "targetPath888");
    process.env.CLI_TARGET_PATH = targetPath;
  });
  program.parse(process.argv);
  if (program.args && program.args.length < 1) {
    program.outputHelp();
    console.log();
  }
}
